import React, { useEffect, useState, useContext, useCallback } from 'react';
import { Button, Spin, Table, Tooltip, Modal, message, Select } from 'antd';
import classNames from 'classnames';
import { withRouter } from 'umi';
import { useRequest } from '@/hooks';

import BizIcon from '@/components/BizIcon';
import { isSuccess } from '@/utils/request';
import If from '@/components/If';
import BottomAction from '@/components/BottomAction';
import authHelper from '@/utils/auth/helper';
import { numberFormat } from '@/utils/formatterUtil';

import { shgFundsService } from '@/services/salaryManage/salaryCalculateService';
import { getRangeDescription } from '@/pages/SalaryManage/SalaryCalculate/InsuranceFundFile/rangeDescription';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';
import {
    goToProcessApply,
    goToSelfHelpFundsInProcess,
    goToProcessDetail
} from '@/pages/SalaryManage/utils/pageNavigateUtil';
import { PROCESS_TYPE } from '@/pages/SalaryManage/utils/processUtil';
import { insuranceFundFileProcessStatus as processStatus } from '@/pages/SalaryManage/enum';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';

import salaryStyle from '@/pages/SalaryManage/salaryManage.less';
import { BaseSettingContext } from '@/pages/SalaryManage/constant/BaseSettingContext';
import DetailModal from './DetailModal';
import { ApproveInfoContext } from './ApproveInfoContext';
import ProcessStatusTag from '../components/ProcessStatusTag';
import pageStyle from './index.less';

const { Option } = Select;

// 0 已生效,1待生效
const EFFECT_IN = 0;

// 按钮权限
const AUTH_CODE = {
    ADD: 'finance:salary:computation:social:shg:add',
    EDIT: 'finance:salary:computation:social:shg:edit',
    DEL: 'finance:salary:computation:social:shg:delete'
};

// 表格列表数据定义
const tableColumns = (operateConfig, decimalPlaces) => {
    const rel = [
        {
            title: '雇员该自然月薪资总额',
            dataIndex: '_amtLevel',
            align: 'left',
            render(text, row) {
                return getRangeDescription(
                    numberFormat(row.twStartAmt, decimalPlaces),
                    row.twStartAmtSign,
                    numberFormat(row.twEndAmt, decimalPlaces),
                    row.twEndAmtSign,
                    '$'
                );
            }
        },
        {
            title: '雇员扣除额',
            dataIndex: 'shgAmt',
            width: 280,
            align: 'left',
            render(text) {
                return numberFormat(text, decimalPlaces, ',', '.', '$');
            }
        }
    ];

    if (operateConfig) {
        const { onEdit, onDelete, disabled } = operateConfig;

        rel.push({
            title: '操作',
            dataIndex: '_operate',
            width: 100,
            fixed: 'right',
            render(text, record) {
                return (
                    <AutoDivider>
                        <If condition={authHelper.checkCode(AUTH_CODE.EDIT)}>
                            <Tooltip title="编辑">
                                <Button
                                    className={classNames(salaryStyle.operateIcon)}
                                    onClick={() => onEdit(record)}
                                    disabled={disabled}
                                >
                                    <BizIcon type="listfunction_edit_icon_default" />
                                </Button>
                            </Tooltip>
                        </If>
                        <If condition={authHelper.checkCode(AUTH_CODE.DEL)}>
                            <Tooltip title="删除">
                                <Button
                                    className={classNames(salaryStyle.operateIcon)}
                                    disabled={disabled}
                                    onClick={() => onDelete(record)}
                                >
                                    <BizIcon type="DeleteIcon" />
                                </Button>
                            </Tooltip>
                        </If>
                    </AutoDivider>
                );
            }
        });
    }

    return rel;
};

const SelfHelpFund = ({ organizationCode, shgId = '', location }) => {
    const [loading, setLoading] = useState(false);
    // 种族列表
    const [raceList, setRaceList] = useState([]);
    // 种族id
    const [raceId, setRaceId] = useState('');
    // 当前页面信息
    const [pageInfo, setPageInfo] = useState({});
    // 审批详情
    const [approveInfo, setApproveInfo] = useState({});
    // 是否显示新增、编辑框
    const [detailModalVisible, setDetailModalVisible] = useState(false);
    // 编辑的内容
    const [editModel, setEditModel] = useState({});
    // 是否显示重置弹窗
    const [resetVisible, setResetVisible] = useState(false);
    // 待审批信息
    const { setApproveInfo: setApproveInfoContext } = useContext(ApproveInfoContext);
    const {
        baseSetting: { scale: decimalPlaces }
    } = useContext(BaseSettingContext);

    const { run: runPageInfo } = useRequest(params => shgFundsService.queryShgDetail(params), { manual: true });
    const { run: getRaceList } = useRequest(params => shgFundsService.queryShgRaceList(params), { manual: true });

    const effect = location.query.effect ? +location.query.effect : EFFECT_IN;

    // 获取页面信息，接口顺序2
    const getPageInfo = useCallback(async () => {
        setLoading(true);

        runPageInfo({
            id: raceId,
            effect: EFFECT_IN === effect ? 0 : 1
        })
            .then(response => {
                setLoading(false);
                if (isSuccess(response)) {
                    setPageInfo(response.data);
                    if (EFFECT_IN !== effect) {
                        // 设置流程信息，【待生效档案】有用到
                        setApproveInfoContext(response.data);
                    }
                } else {
                    message.error(response.msg);
                }
            })
            .catch(() => {
                setLoading(false);
            });
    }, [raceId]);

    // 查询种族列表，接口顺序1
    const search = useCallback(async () => {
        setLoading(true);

        getRaceList({
            organizationCode,
            effect: EFFECT_IN === effect ? 0 : 1
        })
            .then(searchResponse => {
                setLoading(false);
                if (isSuccess(searchResponse)) {
                    const raceIds = searchResponse.data || [];
                    setRaceList(raceIds);
                    let id = '';
                    if (raceIds.find(ele => ele.id === shgId)) {
                        id = shgId;
                    } else {
                        // 没值时默认取第一个
                        const raceDefault = raceIds[0];
                        ({ id } = raceDefault);
                    }
                    setRaceId(id);
                } else {
                    message.error(searchResponse.msg);
                }
            })
            .catch(() => {
                setLoading(false);
            });
    }, [organizationCode]);
    // 切换种族列表
    const onRacialType = id => {
        if (id) {
            setRaceId(id);
        }
    };

    const onAdd = () => {
        setDetailModalVisible(true);
        setEditModel({ shgFundId: raceId });
    };

    const onEdit = record => {
        setDetailModalVisible(true);
        setEditModel({ ...record });
    };

    const onDelete = record => {
        Modal.confirm({
            content: (
                <>
                    您确定要删除【
                    {getRangeDescription(
                        record.twStartAmt,
                        record.twStartAmtSign,
                        record.twEndAmt,
                        record.twEndAmtSign,
                        '$'
                    )}
                    】雇员该自然月薪资总额吗？
                </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk() {
                setLoading(true);
                shgFundsService
                    .deleteShgDetail({ id: record.id, shgFundId: record.shgFundId })
                    .then(response => {
                        if (isSuccess(response)) {
                            getPageInfo();
                        } else {
                            message.error(response.msg);
                        }
                        setLoading(false);
                    })
                    .catch(() => {
                        setLoading(false);
                    });
            }
        });
    };

    const onModalOk = () => {
        setDetailModalVisible(false);
        getPageInfo();
    };

    // 是否可编辑
    const resetAble = () => !!pageInfo?.resetAble;
    // 是否可进入下一步
    const nextAble = () => !!pageInfo?.nextAble;

    // 重置
    const doReset = () => {
        setLoading(true);
        shgFundsService
            .resetShg({ shgId: raceId })
            .then(response => {
                if (!isSuccess(response)) {
                    message.warn(response.msg);
                    return;
                }
                setResetVisible(false);
                message.success('重置成功！');
                getPageInfo();
            })
            .finally(() => {
                setLoading(false);
            });
    };
    const onNext = async () => {
        // 获取查询条件
        setLoading(true);
        try {
            const response = await shgFundsService.queryShgCheck({
                shgId: raceId
            });
            setLoading(false);
            if (!isSuccess(response)) {
                message.warn(response.msg);
                return;
            }
        } catch (e) {
            setLoading(false);
        }
        goToProcessApply(
            PROCESS_TYPE.SALARY_SET_SHG_APPLY,
            { shgId: raceId, organizationCode },
            '没有找到分类为【种族自助金提交审批流程】的流程，请先配置流程'
        );
    };

    useEffect(() => {
        if (organizationCode) {
            search();
        }
    }, [organizationCode]);

    useEffect(() => {
        if (raceId) {
            getPageInfo();
            // 获取审批详情状态
            shgFundsService.queryApproveDetail({ shgId: raceId }).then(response => {
                if (isSuccess(response)) {
                    setApproveInfo(response.data);
                }
            });
        }
    }, [raceId]);

    return (
        <Spin spinning={loading}>
            <div className={classNames(pageStyle.header)}>
                <TwoColHead
                    left={
                        <>
                            <Select
                                showSearch
                                placeholder="请选择"
                                onChange={onRacialType}
                                value={raceId}
                                style={{ minWidth: '208px' }}
                                dropdownStyle={{ maxHeight: 350, overflow: 'auto' }}
                            >
                                {raceList.map(race => (
                                    <Option key={race.id} value={race.id}>
                                        {race.singaporeRaceName}
                                    </Option>
                                ))}
                            </Select>

                            {EFFECT_IN === effect ? (
                                <Button
                                    type="primary"
                                    ghost
                                    onClick={() => goToSelfHelpFundsInProcess(organizationCode, raceId)}
                                >
                                    待生效档案
                                </Button>
                            ) : null}

                            <Button
                                type="primary"
                                ghost
                                onClick={() =>
                                    goToProcessDetail({
                                        processDefinitionId: approveInfo?.processDefinitionId,
                                        processInstanceId: approveInfo?.processId
                                    })
                                }
                                disabled={!(approveInfo.processDefinitionId && approveInfo.processId)}
                            >
                                查看审批详情
                            </Button>
                        </>
                    }
                    right={
                        <If condition={EFFECT_IN === effect && authHelper.checkCode(AUTH_CODE.ADD)}>
                            <Button
                                style={{ width: '88px' }}
                                type="primary"
                                onClick={onAdd}
                                disabled={processStatus.APPROVING === pageInfo?.processStatus}
                            >
                                新增
                            </Button>
                        </If>
                    }
                    style={{ marginTop: '0' }}
                />

                <div className={pageStyle.title}>
                    <header className={pageStyle.h1}>
                        种族自助金维护表
                        <ProcessStatusTag
                            status={pageInfo?.processStatus}
                            className={salaryStyle.ml8}
                            style={{ position: 'absolute', top: '3px' }}
                        />
                    </header>
                </div>
            </div>

            <div>
                <Table
                    columns={tableColumns(
                        EFFECT_IN === effect
                            ? {
                                  onEdit,
                                  onDelete,
                                  disabled: processStatus.APPROVING === pageInfo?.processStatus,
                                  pageInfo
                              }
                            : null,
                        decimalPlaces
                    )}
                    rowKey="id"
                    bordered
                    dataSource={pageInfo?.rows}
                    pagination={false}
                />
            </div>

            <If condition={EFFECT_IN === effect}>
                <BottomAction>
                    <Button onClick={() => setResetVisible(true)} disabled={!resetAble()}>
                        重置
                    </Button>
                    <Button type="primary" onClick={onNext} disabled={!nextAble()}>
                        下一步
                    </Button>
                    <Modal
                        visible={resetVisible}
                        title="重置"
                        okText="确定"
                        cancelText="取消"
                        onOk={doReset}
                        onCancel={() => setResetVisible(false)}
                        width={480}
                        centered
                    >
                        <div style={{ margin: '30px 20px' }}>
                            重置后所有数据将回退到上次审批通过的结果，是否确定重置？
                        </div>
                    </Modal>
                </BottomAction>
            </If>
            <If condition={detailModalVisible}>
                <DetailModal
                    visible={detailModalVisible}
                    model={editModel}
                    onOk={onModalOk}
                    onlyUpdate={!!editModel.id}
                    onCancel={() => setDetailModalVisible(false)}
                />
            </If>
        </Spin>
    );
};

export default withRouter(SelfHelpFund);
